<?php

require_once APPPATH."/libraries/Thumbnails.php";


/* Note: This thumbnail creation script requires the GD PHP Extension.  
  If GD is not installed correctly PHP does not render this page correctly
  and SWFUpload will get "stuck" never calling uploadSuccess or uploadError
 */

// Get the session Id passed from SWFUpload. We have to do this to work-around the Flash Player Cookie Bug
if (isset($_POST["PHPSESSID"])) {
    session_id($_POST["PHPSESSID"]);
}

session_start();
ini_set("html_errors", "0");

//Set response
$response = array(
    'error'     =>  1,
    'message'   =>  'ERROR'
);

// Check the upload
if (!isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) || $_FILES["Filedata"]["error"] != 0) {
    $response['message'] =  "ERROR:invalid upload";
    echo json_encode($response); exit(0);
}

//Get File extension
$fileExt = strtolower(substr($_FILES['Filedata']['name'], -4));
$fileName = md5($_FILES['Filedata']['name']);
$tempFile = $_FILES['Filedata']['tmp_name'];

//Check folder
$folder = isset($_POST['folder'])?$_POST['folder']:'/uploads/images/';

//Make dir
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $folder . date('Y') . '/';
if (!is_dir($targetPath)) {
    mkdir(str_replace('//', '/', $targetPath), 0777, true);
}
$targetPath.= date('m') . '/';
if (!is_dir($targetPath)) {
    mkdir(str_replace('//', '/', $targetPath), 0777, true);
}
$targetPath.= date('d') . '/';
if (!is_dir($targetPath)) {
    mkdir(str_replace('//', '/', $targetPath), 0777, true);
}
$targetFile =  str_replace('//','/',$targetPath) . $fileName . $fileExt;

//Move file from tmp to folder upload
move_uploaded_file($tempFile, $targetFile);

//Get watermark path
$watermarkPath = $_SERVER['DOCUMENT_ROOT'].'/static/images/watermark.png';
// creating png image of watermark
$watermark = imagecreatefrompng($watermarkPath);  
// getting dimensions of watermark image
$watermark_width = imagesx($watermark);
$watermark_height = imagesy($watermark);

// getting the dimensions of original image
$imgsize = getimagesize($targetFile);
// placing the watermark 5px from bottom and right
$dest_x = $imgsize[0] - $watermark_width - 5;
$dest_y = $imgsize[1] - $watermark_height - 5;

//Get target file
switch($fileExt)
{
    case ".jpg":
        $image = imagecreatefromjpeg($targetFile);
        break;
    case ".png":
        $image = imagecreatefrompng($targetFile);
        break;
    case ".gif":
        $image = imagecreatefromgif($targetFile);
        break;
}

// blending the images together
imagealphablending($image, true);
imagealphablending($watermark, true);

// creating the new image
imagecopy($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height);

// Build the thumbnail
$thumb_w = 200; //New width of image
$thumb_h = $imgsize[1]/$imgsize[0]*$thumb_w; //This maintains proportions

$picture = imagecreatetruecolor($thumb_w, $thumb_h);

imagealphablending($image, true);
imagesavealpha($picture, true);

$bool = imagecopyresampled($picture, $image, 0, 0, 0, 0, $thumb_w, $thumb_h, $imgsize[0], $imgsize[1]);

if($bool)
{
    switch($fileExt)
    {
        case ".jpg":
            imagejpeg($image, $targetPath.$fileName.$fileExt);
            imagejpeg($picture, $targetPath.$fileName."_thumb".$fileExt);
            break;
        case ".png":
            imagepng($image, $targetPath.$fileName.$fileExt);
            imagepng($picture, $targetPath.$fileName."_thumb".$fileExt);
            break;
        case ".gif":
            imagegif($image, $targetPath.$fileName.$fileExt);
            imagegif($picture, $targetPath.$fileName."_thumb".$fileExt);
            break;
    }
}

// destroying and freeing memory
imagedestroy($watermark);
imagedestroy($picture);
imagedestroy($image);

//Set response
$response = array(
    'error'     =>  0,
    'message'   =>  'success',
    'body'      =>  array(
        'FILEID'    =>  $_POST["PHPSESSID"],
        'FILEURL'   => str_replace($_SERVER['DOCUMENT_ROOT'], '', $targetPath . $fileName . $fileExt), 
        'THUMBURL'  => str_replace($_SERVER['DOCUMENT_ROOT'], '', $targetPath . $fileName . '_thumb' . $fileExt)
    )
);

//Return response
echo json_encode($response); exit(0);

?>